package vn.cuhanh;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import vn.cuhanh.bean.ShareInfo;
import vn.cuhanh.fragment.AwardFragment;
import vn.cuhanh.utils.HelperFunc;
import vn.cuhanh.utils.LoginHelper;
import vn.cuhanh.utils.ShareFacebook;
import vn.cuhanh.utils.ShareZingMe;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.facebook.Session;

public class ShareActivity extends Activity {
	
	public static final int CONFIRM_SHARING_REQUEST_CODE = 1560;
	public static final int FACEBOOK_LOGIN_REQUEST_CODE = 1561;
	public static final int CONFIRM_SHARING_OK = 1;
	public static final int CONFIRM_SHARING_CANCEL = 0;
	public static final int CONFIRM_SHARING_LOGIN_ANOTHER_ACCOUNT = -1;
	public static final int DESTINATION_ZING_ME = 1;
	public static final int DESTINATION_FACEBOOK = 2;
//	private static final List<String> READ_PERMISSIONS = Arrays.asList("user_location", "user_birthday", "user_likes");
	public static ShareInfo shareInfo;
//	private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
//	private boolean pendingPublishReauthorization = false;
	private static final String TAG = "Share";
	public ProgressDialog progress;
	private boolean areButtonsDisabled;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share);
	    getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
		
		Button btnClose = (Button) findViewById(R.id.share_btn_close);
		btnClose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ShareActivity.this, "share_activity", "btn_close_press", "btn_close_press");
				if(areButtonsDisabled) {
					return;
				}
				onBackPressed();
			}
		});
		
		if(shareInfo == null) {
			ShareZingMe.showShareUnknownFail(this);
			onBackPressed();
			return;
		}
		
		ImageView btShareZingMe = (ImageView)findViewById(R.id.share_zingme);
		btShareZingMe.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ShareActivity.this, "share_activity", "btn_share_zing_me_press", "btn_share_zing_me_press");
				if(areButtonsDisabled) {
					return;
				}
				if(shareInfo != null) {
					ShareZingMe.confirmSharingZingMe(ShareActivity.this, shareInfo);
				}
			}
		});
		ImageView btShareFacebook = (ImageView)findViewById(R.id.share_facebook);
		btShareFacebook.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ShareActivity.this, "share_activity", "btn_share_facebook_press", "btn_share_facebook_press");
				if(areButtonsDisabled) {
					return;
				}
				shareFacebook();
			}
		});
//		LoginButton btnLoginFacebook = (LoginButton)findViewById(R.id.facebook_login_button);
//		btnLoginFacebook.clearPermissions();
//		btnLoginFacebook.setPublishPermissions(PUBLISH_PERMISSIONS);
		getDownloadRefFromServer();
	}
	
	public void disableButtonsTmp(){
		areButtonsDisabled = true;
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				areButtonsDisabled = false;
			}
		}, (long)1000);
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}
	@Override
	public void onResume() {
		super.onResume();
		// For scenarios where the main activity is launched and user
	    // session is not null, the session state change notification
	    // may not be triggered. Trigger it if it's open/closed.
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	@Override
	public void onPause() {
		super.onPause();
	}
	
	public static void showShareUnknownFail(final Context ctx) {
		((Activity)ctx).runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				HelperFunc.showSimpleAlertDialog(ctx, ctx.getResources().getString(R.string.shareFailTitle), 
						ctx.getResources().getString(R.string.shareFailMessage), 
						ctx.getResources().getString(R.string.bt_ok_title), null, null, null, true);
			}
		});
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    
	    if(requestCode == CONFIRM_SHARING_REQUEST_CODE) {
	    	if(resultCode != RESULT_OK) {
	    		return;
	    	}
	    	int result = data.getExtras().getInt("result");
	    	int destination = data.getExtras().getInt("destination");
	    	switch (result) {
			case CONFIRM_SHARING_OK:
				if(destination == DESTINATION_ZING_ME) {
					handleConfirmShareZingMeOk();
				} else if (destination == DESTINATION_FACEBOOK) {
					handleConfirmShareFacebookOk();
				}
				break;
			case CONFIRM_SHARING_LOGIN_ANOTHER_ACCOUNT:
				if(destination == DESTINATION_ZING_ME) {
					LoginHelper loginHelper = LoginHelper.getInstance();
					loginHelper.logout(this);
					// request login
					ShareZingMe.requestLoginAndShareZingMe(this, shareInfo);
				} else if(destination == DESTINATION_FACEBOOK) {
				}
				break;
			default: //CONFIRM_SHARING_CANCEL
				break;
			}
	    } else if (requestCode == FACEBOOK_LOGIN_REQUEST_CODE) {
	    	if(resultCode != RESULT_OK) {
	    		return;
	    	}
	    	shareFacebook();
//	    	int result = data.getExtras().getInt("result");
//	    	switch (result) {
//			case LoginFacebookActivity.LOGIN_OK:
//				break;
//			case LoginFacebookActivity.LOGIN_CANCEL:
//				break;
//			default:
//				break;
//			}
	    }
	}
	public void handleConfirmShareZingMeOk() {
		isSharingProcessing = true;
		progress = ProgressDialog.show(this, null, getResources().getString(R.string.share_progress_dialog_message));
		ShareZingMe.shareZingMe(this, shareInfo, new Runnable() { //success
			@Override
			public void run() {
				// TODO Auto-generated method stub
				isSharingProcessing = false;
				progress.dismiss();
				if(shareInfo.getActionId() != 0) {
					getScoreBySharing(ShareZingMe.lastPostId, DESTINATION_ZING_ME, shareInfo.getActionId());
				} else {
					HelperFunc.showAlertDialogOnUiThread(ShareActivity.this, getResources().getString(R.string.shareSuccessTitle), getResources().getString(R.string.shareSuccessMessage));
				}
			}
		},
		new Runnable() { //fail
			@Override
			public void run() {
				// TODO Auto-generated method stub
				isSharingProcessing = false;
				progress.dismiss();
				Log.d("shareActivity", "unknown fail");
				showShareUnknownFail(ShareActivity.this);
			}
		}, 
		new Runnable() { //cancelled
			@Override
			public void run() {
				// TODO Auto-generated method stub
				isSharingProcessing = false;
//				progress.dismiss();
			}
		});
	}
	public void handleConfirmShareFacebookOk() {
		try {
			isSharingProcessing = true;
			progress = ProgressDialog.show(this, null, getResources().getString(R.string.share_progress_dialog_message));
			ShareFacebook shareFacebookUtil = ShareFacebook.getInstance(this);
			shareFacebookUtil.publishStory(shareInfo, new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					isSharingProcessing = false;
					progress.dismiss();
					if(shareInfo.getActionId() != 0) {
						getScoreBySharing(ShareFacebook.lastPostId, DESTINATION_FACEBOOK, shareInfo.getActionId());
					} else {
						HelperFunc.showAlertDialogOnUiThread(ShareActivity.this, getResources().getString(R.string.shareSuccessTitle), getResources().getString(R.string.shareSuccessMessage));
					}
				}
			}, new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					isSharingProcessing = false;
					progress.dismiss();
				}
			});
		} catch (Exception e) {
			// TODO: handle exception
			HelperFunc.readStackTrace(e);
		}
	}
	public static boolean isSharingProcessing = false;
	@Override
	public void onBackPressed() {
		Log.d("share activity", "onback pressed");
		if(isSharingProcessing) {
			return;
		}
		super.onBackPressed();
	}
	
	public void shareFacebook() {
		try {
			Session session = Session.getActiveSession();
			ShareFacebook shareFacebookUtil = ShareFacebook.getInstance(this);
			if(session == null) {
		        session = new Session.Builder(this).build();
		        Session.setActiveSession(session);
				shareFacebookUtil.facebookRequestLogin();
				return;
			}
			if(!session.isOpened()) {
				shareFacebookUtil.facebookRequestLogin();
				return;
			}
			//publishStory();
			shareFacebookUtil.confirmSharingFacebook(shareInfo);
		} catch (Exception e) {
			// TODO: handle exception
			HelperFunc.readStackTrace(e);
		}
	}
	
	public void getScoreBySharing(String postId, int destination, int actionId) {
		final String url = getResources().getString(R.string.getScoreBySharingUrl)
					.replace("post_id", postId)
					.replace("user_name", MainActivity.username == null ? "" : MainActivity.username)
					.replace("action_id", String.valueOf(actionId))
					.replace("post_to", String.valueOf(destination));
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String response = HelperFunc.getDataFromSv(url);
				if(response == null) {
					HelperFunc.showAlertDialogOnUiThread(ShareActivity.this, null, getResources().getString(R.string.no_network_2));
					return;
				} 
				try {
					JSONObject jsonRes = new JSONObject(response);
					int result = jsonRes.getInt("result");
					if(result == -2 || result == -3 || result == -4) {
						HelperFunc.showAlertDialogOnUiThread(ShareActivity.this, 
								getResources().getString(R.string.shareSuccessTitle), 
								getResources().getString(R.string.shareSuccessMessage));
						return;
					}
					int total = jsonRes.getInt("totalScore");
					if(MainActivity.userAccount != null) {
						MainActivity.userAccount.setDndScore(total);
					}
					if(jsonRes.has("remainDndScore") && !jsonRes.isNull("remainDndScore")) {
						AwardFragment.remainDndScore = jsonRes.getInt("remainDndScore");
					}
					if(result == 1) {
						if(MainActivity.isLogin) {
							int score = jsonRes.getInt("dailyScore");
							HelperFunc.showAlertDialogOnUiThread(ShareActivity.this, getResources().getString(R.string.shareSuccessTitle), 
	                				getResources().getString(R.string.minigame_click_success)
	                					.replace("minigame_name", getResources().getString(R.string.share))
	                					.replace("minigame_score", String.valueOf(score)));
//                					.replace("minigame_score", String.valueOf(30)));
						} else {
							HelperFunc.showAlertDialogOnUiThread(ShareActivity.this, getResources().getString(R.string.shareSuccessTitle), 
	                				getResources().getString(R.string.share_success_login_to_gain_score));
						}
					} else if(result == -1) {
						HelperFunc.showAlertDialogOnUiThread(ShareActivity.this, getResources().getString(R.string.shareSuccessTitle), 
                				getResources().getString(R.string.share_success_wait));
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		thread.start();
	}
	
	public void facebookRequestLogout() {
		Session session = Session.getActiveSession();
		session.closeAndClearTokenInformation();
	}
	
	public void getDownloadRefFromServer() {
		if(downloadRef != null) {
			return;
		}
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String res = HelperFunc.getDataFromSv(getResources().getString(R.string.getMaxVersionCodeUrl));
				if(res == null) {
					return;
				}
				try {
					JSONObject jsonRes = new JSONObject(res);
					if(jsonRes.getInt("result") != 1) {
						return;
					}
					downloadRef = jsonRes.getString("downloadRef");
				} catch(Exception e) {
					
				}
			}
		});
		thread.start();
	}
	
	public static String downloadRef = null;
	public static String getDownloadRef(Context ctx) {
		if(downloadRef == null || downloadRef.isEmpty()) {
			return "";
		}
		
		return ctx.getResources().getString(R.string.downloadRefText).replace("download_ref", downloadRef);
	}
}
